package com.bodystm.temperature.controller;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.bodystm.temperature.bed.Bed;
import com.bodystm.temperature.bed.BedService;
import com.bodystm.temperature.patient.Patient;
import com.bodystm.temperature.patient.PatientBedDao;
import com.bodystm.temperature.patient.PatientBedService;
import com.bodystm.temperature.patient.PatientBedUser;
import com.bodystm.temperature.patient.PatientEquip;
import com.bodystm.temperature.patient.PatientEquipService;
import com.bodystm.temperature.patient.PatientService;
import com.bodystm.temperature.server.Temperature;
import com.bodystm.temperature.server.TemperatureService;
import com.bodystm.temperature.server.UrineBag;
import com.bodystm.temperature.server.UrineBagService;
import com.bodystm.temperature.system.SystemSetting;
import com.bodystm.temperature.system.SystemSettingService;
import com.bodystm.temperature.web.DeviceSettings;
import com.bodystm.temperature.web.EasyUiMessage;
import com.bodystm.temperature.web.TemperatureDevice;
import com.bodystm.temperature.web.UrineBagDevice;
import com.mimosa.common.system.user.TUser;
import com.mimosa.common.system.user.UserContext;
import com.mimosa.common.system.user.UserService;
import com.mimosa.util.config.Page;

@Controller
@RequestMapping("/bed")
public class BedController {
	@Resource
	private BedService bedService;

	@Resource
	private PatientService patientService;

	@Resource 
	private UserService userService;
	
	@Resource
	private TemperatureService temperatureService;
	@Resource
	private UrineBagService urineBagService;
	
	@Autowired
	private PatientBedService patientBedUserService;

	@Autowired
	private PatientBedDao patientBedUserDao;
	@Autowired
	private SystemSettingService systemSettingService;
	@Autowired
	private PatientEquipService patientEquipService;
	
	@RequestMapping("/degreelisten.action")
	public String degreelisten(Model model){
		SystemSetting systemSetting=systemSettingService.getSystemSetting();
		if(systemSetting!=null){
			model.addAttribute("logoPath", systemSetting.getHospitalLogoPath());
		}
		return "bed/degreelisten2";
	}
	
	@RequestMapping("/degreelisten4Admin.action")
	public String degreelisten4Admin(){
		return "bed/degreelisten3";
	}

	@RequestMapping("/index.action")
	public String index(Page<Bed> page, Model model) {
		page = this.bedService.findByPage(page);

		Patient patient = null;
		UrineBag urineBag = null;
		for (Bed bed : page.getResult()) {
			patient = this.patientService.findByBedIdAndEndTimeIsNull(bed.getId());
			if (patient != null) {
				bed.setPatient(patient);
				// 鑾峰彇娓╁害淇℃伅
				if (patient.getEquipNo() != null) {
					urineBag = this.urineBagService.findLatestByEquipNoAndMeasureTime(patient.getEquipNo(),
							patient.getStartTime());
					if (urineBag != null) {
						bed.setUrineBag(urineBag);
					}
				}
			}
		}
		model.addAttribute("start", page.getFirst());
		model.addAttribute("page", page.getPageNo());
		model.addAttribute("rows", page.getPageSize());
		model.addAttribute("totalCount", page.getTotalCount());
		model.addAttribute("bedList", page.getResult());
		return "bed/index";
	}

	@RequestMapping("/edit.action")
	public String edit(String id, String type, Model model) {
		if (StringUtils.isNotBlank(id)) {
			Bed bed = this.bedService.getEntity(id);
			model.addAttribute("bed", bed.getPatient());
		}
		return "bed/" + type;
	}
	
	/*
	 * 获取所有部门
	 */
	@RequestMapping("/listDepartments.action")
	@ResponseBody
	public String listDepartments(){
		List<TUser> users=this.userService.getAll();
		JSONObject bedJSONObject=null;
		JSONArray jSONArray = new JSONArray();
		for(TUser user:users){
			if(user.getUserName().toLowerCase().equals("admin")){
				//users.remove(user);
				continue;
			}
			bedJSONObject = new JSONObject();
			bedJSONObject.put("id", user.getId());
			bedJSONObject.put("name", user.getRealName());
			jSONArray.add(bedJSONObject);
			
		}
		//String json = null;
		
//		ObjectMapper mapper = new ObjectMapper();
//		try {
//			json = mapper.writeValueAsString(listAll);
//		} catch (JsonProcessingException e) {
//
//			json = null;
//		}
		return jSONArray.toString();
	}
	
	@RequestMapping("/getBedsByDepartmentId.action")
	@ResponseBody
	public String getBedsByDepartmentId(String departmentId){
		List<Bed> lstBeds=this.bedService.findList("from Bed t where t.user.id=? and t.status='empty' order by (t.name+0) ASC", departmentId);
		JSONObject bedJSONObject=null;
		JSONArray jSONArray = new JSONArray();
		for(Bed bed:lstBeds){
			bedJSONObject = new JSONObject();
			bedJSONObject.put("id", bed.getId());
			bedJSONObject.put("name", bed.getName());
			jSONArray.add(bedJSONObject);
		}
		return jSONArray.toString();
	}
	
	@RequestMapping("/outBed.action")
	@ResponseBody
	public String outBed(String ids, Model model) {
		this.bedService.outBed(ids);
		return Boolean.TRUE.toString().toLowerCase();
	}

	@ResponseBody
	@RequestMapping("/save.action")
	public String save(Bed bed) {
		this.bedService.saveEntity(bed);
		return Boolean.TRUE.toString().toLowerCase();
	}

//	@ResponseBody
//	@RequestMapping("/add.action")
//	public String add(String bedid) {
//		java.util.List<Bed> lstBed = this.bedService.findList("from Bed t where t.name=? order by t.name ASC", bedid);
//		if (lstBed.size() > 0)
//			return "{\"success\":false,\"bedid\":\"1010\"}";
//		Bed bed = new Bed();
//		bed.setName(bedid);
//		this.bedService.saveEntity(bed);
//		  "{\"success\":true,\"bedid\":\"" + bedid + "\"}";
//	}
	/*
	 * 娣诲姞搴婁綅 by rxz 20151124
	 */
	@ResponseBody
	@RequestMapping("/add.action")
	public String add(String bedid,String concentratorNo,HttpSession session) {
        java.util.List<Bed> lstBed=this.bedService.findList("from Bed t where t.name=? and t.user.id=? order by t.name ASC", bedid,((TUser)session.getAttribute(UserContext.USER_ATTR)).getId());
		if(lstBed.size()>0) return "{\"success\":false,\"bedid\":\""+bedid+"\"}";
		Bed bed=new Bed();
		bed.setName(bedid);
		if(concentratorNo!=null&&concentratorNo.length()>0)
		bed.setConcentratorNo(concentratorNo);
		bed.setStatus("empty");
		bed.setUser((TUser)session.getAttribute(UserContext.USER_ATTR));
		this.bedService.saveEntity(bed);
		return "{\"success\":true,\"bedid\":\""+bedid+"\"}";
	}
	/*
	 * 璁＄畻鍓╀綑鐢甸噺 by rxz
	 */
	private long getTime(Date datestart){
		long n= Math.abs((datestart.getTime()-(new Date()).getTime())/3600000);
		if(n>48)return 0;
		return 48-n;
	}
	@ResponseBody
	@RequestMapping("/stopwarning.action")
	public String stopwarning(String strmac){
		if(DeviceSettings.lstMacs.contains(strmac)){
			UrineBagDevice urineBagDevice=(UrineBagDevice)DeviceSettings.hasDevice.get(strmac);
			urineBagDevice.setWarningOrNot(false);
			return Boolean.TRUE.toString().toLowerCase();	
		}
		return Boolean.FALSE.toString().toLowerCase();
	}
	@ResponseBody
	@RequestMapping("/stopwarning4nosign.action")
	public String stopwarning4nosign(String strmac){
		if(DeviceSettings.lstMacs.contains(strmac)){
			UrineBagDevice urineBagDevice=(UrineBagDevice)DeviceSettings.hasDevice.get(strmac);
			urineBagDevice.setWarningOrNot4NoSign(false);
			return Boolean.TRUE.toString().toLowerCase();	
		}
		return Boolean.FALSE.toString().toLowerCase();
	}
	@ResponseBody
	@RequestMapping("/stopwarning4full.action")
	public String stopwarning4full(String strmac){
		if(DeviceSettings.lstMacs.contains(strmac)){
			UrineBagDevice urineBagDevice=(UrineBagDevice)DeviceSettings.hasDevice.get(strmac);
			urineBagDevice.setWarningOrNot4Full(false);
			return Boolean.TRUE.toString().toLowerCase();	
		}
		return Boolean.FALSE.toString().toLowerCase();
	}
	@ResponseBody
	@RequestMapping("/stopwarning4nopower.action")
	public String stopwarning4nopower(String strmac){
		if(DeviceSettings.lstMacs.contains(strmac)){
			UrineBagDevice urineBagDevice=(UrineBagDevice)DeviceSettings.hasDevice.get(strmac);
			urineBagDevice.setWarningOrNot4NoPower(false);
			return Boolean.TRUE.toString().toLowerCase();	
		}
		return Boolean.FALSE.toString().toLowerCase();
	}
	/*
	 * 鑾峰彇鎵�湁搴婁綅鐨勫垪琛�
	 */
	@ResponseBody
	@RequestMapping("/listAll.action")
	public String listAll(HttpSession session) {
        try {
			java.util.List<Bed> lstBed=this.bedService.findList("from Bed t where t.user.id=? order by (t.name+0) ASC",((TUser)session.getAttribute(UserContext.USER_ATTR)).getId());
			if(lstBed.size()==0) return "{\"total\":0,\"data\":[],\"otherdata:\"[]}";
			JSONArray jSONArray = new JSONArray();
			JSONObject bedJSONObject = null;
			JSONObject personJSONObject = new JSONObject();
			JSONObject personTempJSONObject = null;
			Patient patient=null;
			UrineBag urineBag=null;
			float[] strTemp4degrees=null; float[] strTemp4degree=null;DecimalFormat decimalFormat=new DecimalFormat(".00");//构造方法的字符格式这里如果小数不足2位,会以0补足.
			List<UrineBag> urineBags;
			SimpleDateFormat sdf = new SimpleDateFormat("MM-dd HH:mm");
			SimpleDateFormat sdfDate = new SimpleDateFormat("yyyy-MM-dd");
			SimpleDateFormat sdfTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			SimpleDateFormat sdfHAndM = new SimpleDateFormat("HH:mm");
			float theDegreeOfABed=0;//获取到的某个床位的实时温度
			int theNYOfABed=0;
			int theNLOfABed=0;
			PatientBedUser patientBedUser=null;
			Temperature temperatureLatest=null;//获取剩余电量时使用
			String[] strTimesTemp=null;//临时存放某个床位病人体温数据的时间数据
			Calendar calendar=Calendar.getInstance();
			for (Bed bed : lstBed) {
				bedJSONObject=new JSONObject();
				patient = this.patientService.findByBedIdAndEndTimeIsNull(bed
						.getId());
				if (patient != null) {
					bed.setPatient(patient);
					bed.setStatus("notempty");
					//判断全局变量中是否含有此设备，没有则新建，有则获取,然后获取其中的实时温度最后显示到界面上
					UrineBagDevice urineBagDevice=null;
					//获取实时温度
					boolean ifgetDegree=false;
					if (patient.getEquipNo() != null) {
						//theDegreeOfABed=0;
						/*//判断全局变量中是否含有此设备，没有则新建，有则获取,然后获取其中的实时温度最后显示到界面上
						TemperatureDevice temperatureDevice=null;*/
						if(DeviceSettings.lstMacs.contains(patient.getEquipNo())){
							urineBagDevice=(UrineBagDevice)DeviceSettings.hasDevice.get(patient.getEquipNo());
							if(urineBagDevice!=null){//&&urineBagDevice.getCurrentNY()>0//此条件是为了判定是否已经上过数了
								//bedJSONObject.put("degree",decimalFormat.format(temperatureDevice.getCurrentDegree()));//保留两位小数
								ifgetDegree=true;
								theNYOfABed=urineBagDevice.getCurrentNY();
								theNLOfABed=urineBagDevice.getCurrentNL();
							}
							else{
								
								urineBag = this.urineBagService
										.findLatestByEquipNoAndMeasureTime(
												patient.getEquipNo(),
												patient.getStartTime());
								if (urineBag != null) {
									bed.setUrineBag(urineBag);
									ifgetDegree=true;
									//bedJSONObject.put("degree", (float)(Math.round(temperature.getMeasureNumOne()*10))/10);
									theNYOfABed=urineBag.getNY();
									theNLOfABed=urineBag.getNL();
									urineBagDevice.setCurrentNY(theNYOfABed);
									urineBagDevice.setCurrentNL(theNLOfABed);
								}
							}
						}else{
							//
							DeviceSettings.lstMacs.add(patient.getEquipNo());
							urineBagDevice=new UrineBagDevice();
							urineBagDevice.setStrMac(patient.getEquipNo());
							DeviceSettings.hasDevice.put(patient.getEquipNo(), urineBagDevice);
							urineBag = this.urineBagService
									.findLatestByEquipNoAndMeasureTime(
											patient.getEquipNo(),
											patient.getStartTime());
							if (urineBag != null) {
								bed.setUrineBag(urineBag);
								ifgetDegree=true;
								//bedJSONObject.put("degree", (float)(Math.round(temperature.getMeasureNumOne()*10))/10);
								theNYOfABed=urineBag.getNY();
								theNLOfABed=urineBag.getNL();
							}
						}
					}
					
					bedJSONObject.put("listenstate", "listening");
					if(ifgetDegree){//bed.getTiwen()!=null){
						//bedJSONObject.put("degree",bed.getTiwen().getMeasureNumOne());
						//bedJSONObject.put("degree",decimalFormat.format(bed.getTiwen().getMeasureNumOne()));//保留两位小数
//						bedJSONObject.put("degree",decimalFormat.format(theDegreeOfABed));//保留两位小数
						bedJSONObject.put("NY",theNYOfABed);
						bedJSONObject.put("NL",theNLOfABed);
						
						if(theNLOfABed>=patient.getHighNY()){
							bedJSONObject.put("state", "high");
							urineBagDevice.setWarningType(2);
						}
						else if(theNLOfABed<=patient.getLowNY()){
							if(theNLOfABed>0){
								urineBagDevice.setWarningType(1);
							}else{
								urineBagDevice.setWarningType(0);
							}
							bedJSONObject.put("state", "low");
						}
						else{
							bedJSONObject.put("state", "normal");
							urineBagDevice.setWarningType(0);
							urineBagDevice.setWarningOrNot(true);
						}
						if(theNYOfABed>=2800&&urineBagDevice.isWarningOrNot4Full()){
							bedJSONObject.put("warningOrNot4Full", true);
						}else {
							bedJSONObject.put("warningOrNot4Full", false);
							if(theNYOfABed<2800&&!urineBagDevice.isWarningOrNot4Full()){
								urineBagDevice.setWarningOrNot4Full(true);
							}
							
						}
						bedJSONObject.put("ifWarn",urineBagDevice.isWarningOrNot());
						bedJSONObject.put("warningType",urineBagDevice.getWarningType());
					}
					
					
					bedJSONObject.put("range", patient.getLowNY()+"~"+patient.getHighNY());
					if(patient.getListenStartTime()!=null&&patient.getListenEndTime()!=null)
					bedJSONObject.put("listentime", sdf.format(patient.getListenStartTime())+"~"+sdf.format(patient.getListenEndTime()));
					else if(patient.getListenStartTime()!=null)bedJSONObject.put("listentime", sdf.format(patient.getListenStartTime()));//patient.getListenStartTime()
					bedJSONObject.put("num", patient.getEquipNo());
					if(patient.getListenStartTime()!=null)
					bedJSONObject.put("surplustime", getTime(patient.getListenStartTime()));
					//获取温度贴片的剩余电量
					temperatureLatest=temperatureService.getLatestTemprature(patient.getEquipNo());
					if(temperatureLatest!=null){
						bedJSONObject.put("powerNum", temperatureLatest.getPowerNum());
					}else{
						bedJSONObject.put("powerNum", 100);
					}
					bedJSONObject.put("personinfo", patient.getName()+"-"+patient.getSex()+"-"+patient.getAge()+"岁");
					bedJSONObject.put("name", patient.getName());
					bedJSONObject.put("sex", patient.getSex());
					bedJSONObject.put("age", patient.getAge());
					bedJSONObject.put("diagnosis",patient.getDisease());
					if(patient.getStartTime()!=null)
					bedJSONObject.put("roomtime", sdfTime.format(patient.getStartTime()));//sdfDate
					bedJSONObject.put("sicknum", patient.getMedicalRecordNumber());
					bedJSONObject.put("doctor", patient.getDoctor());
					bedJSONObject.put("patientid", patient.getId());//鑾峰彇鐥呬汉id浠ヤ究鍑洪櫌绛夊悗缁搷浣�
					bedJSONObject.put("num4Correct", patient.getNum4Correct());
					
					
					personTempJSONObject=new JSONObject();
					personTempJSONObject.put("personid", patient.getPersonnelId());
					personTempJSONObject.put("type", patient.getMedicalTreatmentType());
					personTempJSONObject.put("address", patient.getAddress());
					
					//获取贴片工作状态
					patientBedUser =patientBedUserDao.getPatientBedUserByPatientAnddBed(patient.getId(), bed.getId());
					if(patientBedUser!=null&&patientBedUser.getStatusOfDevice()!=null){
						bedJSONObject.put("deviceStatus", patientBedUser.getStatusOfDevice());
						bedJSONObject.put("warningOrNot4NoSign", urineBagDevice.isWarningOrNot4NoSign());
					}else{
						bedJSONObject.put("deviceStatus", 1);
					}
					//超过50小时的提醒相关
					if(urineBagDevice!=null&&urineBagDevice.getWarningOrNot4NoPower()!=null&&urineBagDevice.getWarningOrNot4NoPower()==true){
						bedJSONObject.put("nopower", 1);
					}else{
						
					}
					personJSONObject.put(bed.getName(), personTempJSONObject);
				}
				else{
					bed.setStatus("empty");

				}
				bedJSONObject.put("bedid", bed.getName());
				bedJSONObject.put("idofbed", bed.getId());
				bedJSONObject.put("bedstate", bed.getStatus());
				jSONArray.add(bedJSONObject);

			}
			return "{\"total\":"+lstBed.size()+",\"data\":"+jSONArray.toString()+",\"otherdata\":"+personJSONObject.toString()+"}";
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}
	}
	
	@ResponseBody
	@RequestMapping("/getDegreeByMac.action")
	public String getDegreeByMac(String strMac,String type4Time,HttpSession session) {
		try {
			float[] strTemp4degree=null;
			int[] strTemp4NY=null;
			int[] strTemp4NL=null;
			JSONObject personTempJSONObject = new JSONObject();
			List<UrineBag> urineBags=null;
			SimpleDateFormat sdfHAndM = new SimpleDateFormat("HH:mm");
			SimpleDateFormat sdfH = new SimpleDateFormat("HH:00");
			SimpleDateFormat sdfTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			SimpleDateFormat sdfDateH = new SimpleDateFormat("MM-dd HH:00");
			SimpleDateFormat sdfDateH2 = new SimpleDateFormat("     HH:00");//用于同一天日期不重复显示
			SimpleDateFormat sdfDate = new SimpleDateFormat("MM-dd");
			DecimalFormat decimalFormat=new DecimalFormat(".00");//构造方法的字符格式这里如果小数不足2位,会以0补足.
			String[] strTimesTemp=null;//临时存放某个床位病人体温数据的时间数据
			String[] strDateHsTemp=null;
			Calendar calendar=Calendar.getInstance();
			//
			int datacount=0;
			//续贴功能相关
			List<UrineBag> urineBagsTEmp=null;
			List<PatientEquip> lstPE=patientEquipService.getPatientEquipByMac(strMac);
			String patientID="";
			if(lstPE!=null&&lstPE.size()>0){
				patientID=lstPE.get(0).getPatientID();
			}
			List<PatientEquip> lstPE2=null;
			if(patientID.length()>0){
				lstPE2=patientEquipService.getPatientEquipByPatient(patientID);
				if(lstPE2!=null){
					urineBags=new ArrayList<UrineBag>();
					/*for(int j=0;j<lstPE2.size();j++){
						temperaturesTEmp=this.temperatureService.find24ByEquipNoAndMeasureTime(lstPE2.get(j).getEquipNo());
						if(temperaturesTEmp!=null&&temperaturesTEmp.size()>0)
						temperatures.addAll(temperaturesTEmp);
					}*/
					String strMacs="";
					for(int j=0;j<lstPE2.size();j++){
						strMacs+="'"+lstPE2.get(j).getEquipNo()+"',";
					}
					if(strMacs.length()>0){
						strMacs=strMacs.substring(0,strMacs.length()-1);
						//temperatures = this.temperatureService.find24ByMacsAndMeasureTime(strMacs);
						//根据用户设置的时间间隔类型获取温度数据
//						temperatures = this.temperatureService.findAllByMacs(strMacs);
						int flag=0;
						switch (type4Time) {
						case "5":
							flag = 1;
							urineBags = this.urineBagService.findAllByMacs(strMacs);
							sdfH = new SimpleDateFormat("HH:mm");
							sdfDateH = new SimpleDateFormat("MM-dd HH:mm");
							sdfDateH2= new SimpleDateFormat("HH:mm");
							break;
						case "10":
							flag = 2;
							urineBags = this.urineBagService.findAllByMacs(strMacs);
							sdfH = new SimpleDateFormat("HH:mm");
							sdfDateH = new SimpleDateFormat("MM-dd HH:mm");
							sdfDateH2= new SimpleDateFormat("HH:mm");
							break;
						case "30":
							flag = 6;
							urineBags = this.urineBagService.findAllByMacs(strMacs);
							sdfH = new SimpleDateFormat("HH:mm");
							sdfDateH = new SimpleDateFormat("MM-dd HH:mm");
							sdfDateH2= new SimpleDateFormat("HH:mm");
							break;
						case "60":
							flag = 12;
							urineBags = this.urineBagService.find24ByMacsAndMeasureTime(strMacs);
							sdfH = new SimpleDateFormat("HH:00");
							sdfDateH = new SimpleDateFormat("MM-dd HH:00");
							sdfDateH2= new SimpleDateFormat("HH:00");
							break;
						case "120":
							flag = 24;
							urineBags = this.urineBagService.find24ByMacsAndMeasureTime(strMacs);
							sdfH = new SimpleDateFormat("HH:00");
							sdfDateH = new SimpleDateFormat("MM-dd HH:00");
							sdfDateH2= new SimpleDateFormat("HH:00");
							break;
						default:
							flag = 1;
							break;
						}
						int noTemp=0;
						if(flag<12){
							for(int k=0;k<urineBags.size();k++){
								if(noTemp++%flag!=0)urineBags.remove(k--);
							}
						}else if(flag==24){
							Calendar dateTemp=Calendar.getInstance();
							for(int k=0;k<urineBags.size();k++){
								dateTemp.setTime(urineBags.get(k).getMeasureTime());
								if(dateTemp.get(Calendar.HOUR_OF_DAY)%2==1)
									urineBags.remove(k--);
							}
						}
						
					}
				}
			}
			//temperatures=this.temperatureService.find24ByEquipNoAndMeasureTime(strMac);
					if(urineBags!=null&&urineBags.size()>0){
						Calendar date=Calendar.getInstance();
						/*for(int i=0;i<temperatures.size();i++){
							date.setTime(temperatures.get(i).getMeasureTime());
							if(date.get(Calendar.HOUR_OF_DAY)%2==0)datacount++;
						}
						strTemp4degree=new float[datacount];
						strTimesTemp=new String[datacount];
						strDateHsTemp=new String[datacount];*///20160617体温表格时间间隔由用户设置
//						strTemp4degree=new float[urineBags.size()];
						strTemp4NY=new int[urineBags.size()];
						strTemp4NL=new int[urineBags.size()];
						strTimesTemp=new String[urineBags.size()];
						strDateHsTemp=new String[urineBags.size()];
						int countStr=0;
						String strDateTemp="";
//						List<List<Float>> lstStrTemp4degrees=new ArrayList<List<Float>>();
						List<List<Integer>> lstStrTemp4NYs=new ArrayList<List<Integer>>();
						List<List<Integer>> lstStrTemp4NLs=new ArrayList<List<Integer>>();
						List<List<String>> lstStrTimesTemps=new ArrayList<List<String>>();
//						List<Float> lstdegrees=null; 
						List<Integer> lstNYs=null; 
						List<Integer> lstNLs=null; 
						List<String> lsttimes=null; 
						List<String> dates=new ArrayList<String>();
						for(int i=0;i<urineBags.size();i++){
							//temperatures.get(i).getMeasureTime().getHours()+
							/*date.setTime(temperatures.get(i).getMeasureTime());
							if(date.get(Calendar.HOUR_OF_DAY)%2!=0) continue;*///20160617体温表格时间间隔由用户设置
							if(i==0||i==1){
								personTempJSONObject.put("times", date.get(Calendar.HOUR_OF_DAY));
							}
							//strTemp4degrees[i]=temperatures.get(i).getMeasureNumOne();
							//personTempJSONObject.put("degrees", strTemp4degrees);
							//温度数据保留两位小数
							//strTemp4degree[i]=decimalFormat.format(temperatures.get(i).getMeasureNumOne());
							if(countStr<=strTemp4NY.length-1){
//								strTemp4degree[countStr]=urineBags.get(i).getMeasureNumOne()<34?34:(urineBags.get(i).getMeasureNumOne()>42?42:temperatures.get(i).getMeasureNumOne());//decimalFormat.format(temperatures.get(i).getMeasureNumOne());
								strTemp4NY[countStr]=urineBags.get(i).getNY();
								strTemp4NL[countStr]=urineBags.get(i).getNL();
								strTimesTemp[countStr]=sdfH.format(urineBags.get(i).getMeasureTime());
								if(strDateTemp.length()==0){
//									lstdegrees=new ArrayList<Float>();
									lstNYs=new ArrayList<Integer>();
									lstNLs=new ArrayList<Integer>();
									lsttimes=new ArrayList<String>(); 
//									lstStrTemp4degrees.add(lstdegrees);
									lstStrTemp4NYs.add(lstNYs);
									lstStrTemp4NLs.add(lstNLs);
									lstStrTimesTemps.add(lsttimes);
//									lstdegrees.add(temperatures.get(i).getMeasureNumOne()<34?34:(temperatures.get(i).getMeasureNumOne()>42?42:temperatures.get(i).getMeasureNumOne()));
									lstNYs.add(urineBags.get(i).getNY());
									lstNLs.add(urineBags.get(i).getNL());
									lsttimes.add(sdfH.format(urineBags.get(i).getMeasureTime()));							
									strDateTemp=sdfDate.format(urineBags.get(i).getMeasureTime());
									dates.add(strDateTemp);
									strDateHsTemp[countStr++]=sdfDateH.format(urineBags.get(i).getMeasureTime());
								}else{
									if(strDateTemp.equals(sdfDate.format(urineBags.get(i).getMeasureTime()))){
//										lstdegrees.add(temperatures.get(i).getMeasureNumOne()<34?34:(temperatures.get(i).getMeasureNumOne()>42?42:temperatures.get(i).getMeasureNumOne()));
										lstNYs.add(urineBags.get(i).getNY());
										lstNLs.add(urineBags.get(i).getNL());
										lsttimes.add(sdfH.format(urineBags.get(i).getMeasureTime()));
										strDateHsTemp[countStr++]=sdfDateH2.format(urineBags.get(i).getMeasureTime());
									}else{
//										lstdegrees=new ArrayList<Float>();
										lstNYs=new ArrayList<Integer>();
										lstNLs=new ArrayList<Integer>();
										lsttimes=new ArrayList<String>(); 
										lstStrTemp4NYs.add(lstNYs);
										lstStrTemp4NLs.add(lstNLs);
										lstStrTimesTemps.add(lsttimes);
//										lstdegrees.add(temperatures.get(i).getMeasureNumOne()<34?34:(temperatures.get(i).getMeasureNumOne()>42?42:temperatures.get(i).getMeasureNumOne()));
										lstNYs.add(urineBags.get(i).getNY());
										lstNLs.add(urineBags.get(i).getNL());
										lsttimes.add(sdfH.format(urineBags.get(i).getMeasureTime()));
										strDateTemp=sdfDate.format(urineBags.get(i).getMeasureTime());
										dates.add(strDateTemp);
										strDateHsTemp[countStr++]=sdfDateH.format(urineBags.get(i).getMeasureTime());
									}
									
								}
								//strDateHsTemp[countStr++]=sdfDateH.format(temperatures.get(i).getMeasureTime());
							}
							
						}
						//for()
//						personTempJSONObject.put("degrees4chart", lstStrTemp4degrees);//strTemp4degree
						personTempJSONObject.put("nys4chart", lstStrTemp4NYs);
						personTempJSONObject.put("nls4chart", lstStrTemp4NLs);
						personTempJSONObject.put("times4chart", lstStrTimesTemps);//strTimesTemp
						personTempJSONObject.put("dhs4chart", strDateHsTemp);
						personTempJSONObject.put("dates4Chart", dates);

					}else{
//						personTempJSONObject.put("degrees4chart", null);
						personTempJSONObject.put("nys4chart", null);
						personTempJSONObject.put("nls4chart", null);
						personTempJSONObject.put("times4chart", null);
						personTempJSONObject.put("dhs4chart", null);
						personTempJSONObject.put("dates4Chart", null);
					}
			return personTempJSONObject.toString();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}
		//******************************************************************************************************************************
	}
	@ResponseBody
	@RequestMapping("/listAll4Patients.action")
	public String listAll4Patients(HttpSession session) {
        try {
        	List<Patient> lstPatient=this.patientService.findList("from Patient t where t.user.id=? order by t.startTime DESC",((TUser)session.getAttribute(UserContext.USER_ATTR)).getId());
        	if(lstPatient.size()==0) return "{\"total\":0,\"data\":[],\"otherdata:\"[]}";
        	/*java.util.List<Bed> lstBed=this.bedService.findList("from Bed t where t.user.id=? order by t.name ASC",((TUser)session.getAttribute(UserContext.USER_ATTR)).getId());
			if(lstBed.size()==0) return "{\"total\":0,\"data\":[],\"otherdata:\"[]}";*/
			JSONArray jSONArray = new JSONArray();
			JSONObject bedJSONObject = null;
			JSONObject personJSONObject = new JSONObject();
			JSONObject personTempJSONObject = null;
			//Patient patient=null;
			Bed bed=null;
			UrineBag urineBag=null;
			float[] strTemp4degrees=null; float[] strTemp4degree=null;DecimalFormat decimalFormat=new DecimalFormat(".00");//构造方法的字符格式这里如果小数不足2位,会以0补足.
			List<UrineBag> UrineBags;
			SimpleDateFormat sdf = new SimpleDateFormat("MM-dd HH:mm");
			SimpleDateFormat sdfDate = new SimpleDateFormat("yyyy-MM-dd");
			SimpleDateFormat sdfTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			SimpleDateFormat sdfHAndM = new SimpleDateFormat("HH:mm");
			float theDegreeOfABed=0;//获取到的某个床位的实时温度
			int currentNY=0;
			int currentNL=0;
			PatientBedUser patientBedUser=null;
			Temperature temperatureLatest=null;//获取剩余电量时使用
			String[] strTimesTemp=null;//临时存放某个床位病人体温数据的时间数据
			Calendar calendar=Calendar.getInstance();
			for (Patient patient : lstPatient) {
				bedJSONObject=new JSONObject();
				bed=patient.getBed();
				if (patient != null) {
					bed.setPatient(patient);
					bed.setStatus("notempty");
					//判断全局变量中是否含有此设备，没有则新建，有则获取,然后获取其中的实时温度最后显示到界面上
					UrineBagDevice urineBagDevice=null;
					//获取实时温度
					boolean ifgetDegree=false;
					if (patient.getEquipNo() != null) {
						/*//判断全局变量中是否含有此设备，没有则新建，有则获取,然后获取其中的实时温度最后显示到界面上
						TemperatureDevice temperatureDevice=null;*/
						if(DeviceSettings.lstMacs.contains(patient.getEquipNo())){
							urineBagDevice=(UrineBagDevice)DeviceSettings.hasDevice.get(patient.getEquipNo());
							if(urineBagDevice!=null&&urineBagDevice.getCurrentNL()>0){
								ifgetDegree=true;
								//theDegreeOfABed=temperatureDevice.getCurrentDegree();
								currentNY=urineBagDevice.getCurrentNY();
								currentNL=urineBagDevice.getCurrentNL();
							}
							else{
								
								urineBag = this.urineBagService
										.findLatestByEquipNoAndMeasureTime(
												patient.getEquipNo(),
												patient.getStartTime());
								if (urineBag != null) {
									bed.setUrineBag(urineBag);
									ifgetDegree=true;
									//bedJSONObject.put("degree", (float)(Math.round(temperature.getMeasureNumOne()*10))/10);
									//theDegreeOfABed=temperature.getMeasureNumOne();
									currentNY=urineBag.getNY();
									currentNL=urineBag.getNL();
								}
							}
						}else{
							//
							DeviceSettings.lstMacs.add(patient.getEquipNo());
							urineBagDevice=new UrineBagDevice();
							urineBagDevice.setStrMac(patient.getEquipNo());
							DeviceSettings.hasDevice.put(patient.getEquipNo(), urineBagDevice);
							urineBag = this.urineBagService
									.findLatestByEquipNoAndMeasureTime(
											patient.getEquipNo(),
											patient.getStartTime());
							if (urineBag != null) {
								bed.setUrineBag(urineBag);
								ifgetDegree=true;
								//bedJSONObject.put("degree", (float)(Math.round(temperature.getMeasureNumOne()*10))/10);
//								theDegreeOfABed=temperature.getMeasureNumOne();
								currentNY=urineBag.getNY();
								currentNL=urineBag.getNL();
							}
						}
					}
					
					bedJSONObject.put("listenstate", "listening");
					if(ifgetDegree){//bed.getTiwen()!=null){
//						bedJSONObject.put("degree",decimalFormat.format(theDegreeOfABed));//保留两位小数
						bedJSONObject.put("NY",currentNY);
						bedJSONObject.put("NL",currentNL);
						//getTime(patient.getListenStartTime())
						
						if(currentNY>=patient.getHighNY()){
							bedJSONObject.put("state", "high");
							urineBagDevice.setWarningType(2);
						}
						else if(currentNY<=patient.getLowNY()){
							urineBagDevice.setWarningType(1);
							bedJSONObject.put("state", "low");
						}
						else{
							bedJSONObject.put("state", "normal");
							urineBagDevice.setWarningType(0);
							urineBagDevice.setWarningOrNot(true);
						}
						bedJSONObject.put("ifWarn",urineBagDevice.isWarningOrNot());
						bedJSONObject.put("warningType",urineBagDevice.getWarningType());
					}
					bedJSONObject.put("range", patient.getLowNY()+"~"+patient.getHighNY());
					if(patient.getListenStartTime()!=null&&patient.getListenEndTime()!=null)
					bedJSONObject.put("listentime", sdf.format(patient.getListenStartTime())+"~"+sdf.format(patient.getListenEndTime()));
					else if(patient.getListenStartTime()!=null)bedJSONObject.put("listentime", sdf.format(patient.getListenStartTime()));//patient.getListenStartTime()
					bedJSONObject.put("num", patient.getEquipNo());
					if(patient.getListenStartTime()!=null)
					bedJSONObject.put("surplustime", getTime(patient.getListenStartTime()));
					//获取温度贴片的剩余电量
					temperatureLatest=temperatureService.getLatestTemprature(patient.getEquipNo());
					if(temperatureLatest!=null){
						bedJSONObject.put("powerNum", temperatureLatest.getPowerNum());
					}else{
						bedJSONObject.put("powerNum", 100);
					}
					bedJSONObject.put("personinfo", patient.getName()+"-"+patient.getSex()+"-"+patient.getAge()+"岁");
					bedJSONObject.put("name", patient.getName());
					bedJSONObject.put("sex", patient.getSex());
					bedJSONObject.put("age", patient.getAge());
					bedJSONObject.put("diagnosis",patient.getDisease());
					if(patient.getStartTime()!=null)
					bedJSONObject.put("roomtime", sdfTime.format(patient.getStartTime()));//sdfDate
					bedJSONObject.put("sicknum", patient.getMedicalRecordNumber());
					bedJSONObject.put("doctor", patient.getDoctor());
					bedJSONObject.put("patientid", patient.getId());//鑾峰彇鐥呬汉id浠ヤ究鍑洪櫌绛夊悗缁搷浣�
					bedJSONObject.put("num4Correct", patient.getNum4Correct());
					
					
					personTempJSONObject=new JSONObject();
					personTempJSONObject.put("personid", patient.getPersonnelId());
					personTempJSONObject.put("type", patient.getMedicalTreatmentType());
					personTempJSONObject.put("address", patient.getAddress());
					
					//获取贴片工作状态
					patientBedUser =patientBedUserDao.getPatientBedUserByPatientAnddBed(patient.getId(), bed.getId());
					if(patientBedUser!=null&&patientBedUser.getStatusOfDevice()!=null){
						bedJSONObject.put("deviceStatus", patientBedUser.getStatusOfDevice());
						bedJSONObject.put("warningOrNot4NoSign", urineBagDevice.isWarningOrNot4NoSign());
					}else{
						bedJSONObject.put("deviceStatus", 1);
					}
					//超过50小时的提醒相关
					if(urineBagDevice!=null&&urineBagDevice.getWarningOrNot4NoPower()!=null&&urineBagDevice.getWarningOrNot4NoPower()==true){
						bedJSONObject.put("nopower", 1);
					}else{
						
					}
					personJSONObject.put(bed.getName(), personTempJSONObject);
				}
				else{
					bed.setStatus("empty");

				}
				bedJSONObject.put("bedid", bed.getName());
				bedJSONObject.put("idofbed", bed.getId());
				bedJSONObject.put("bedstate", bed.getStatus());
				jSONArray.add(bedJSONObject);

			}
			return "{\"total\":"+lstPatient.size()+",\"data\":"+jSONArray.toString()+",\"otherdata\":"+personJSONObject.toString()+"}";
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}
	}
	// @ResponseBody
	// @RequestMapping("/listAll.action")
	// public String listAll() {
	// java.util.List<Bed> lstBed=this.bedService.findList("from Bed t order by
	// t.name ASC");
	// if(lstBed.size()>0) return "{\"success\":false,\"bedid\":\"1010\"}";
	// Bed bed=new Bed();
	// bed.setName(bedid);
	// this.bedService.saveEntity(bed);
	// return "{\"success\":true,\"bedid\":\""+bedid+"\"}";
	// }

	@ResponseBody
	@RequestMapping(value = "/show.action", produces = { "application/json;charset=UTF-8" })
	public String show(String id) {
		Bed bed = this.bedService.getEntity(id);
		String data = "\"\"";
		if (bed != null && bed.getPatient() != null) {
			data = String.format("{\"equipNo\":\"%s\",\"name\":\"%s\",\"id\":\"%s\"}", bed.getPatient().getEquipNo(),
					bed.getPatient().getName(), bed.getPatient().getId());
		}
		EasyUiMessage message = new EasyUiMessage();
		message.setData(data);
		return message.toString();
	}

	@ResponseBody
	@RequestMapping("/update.action")
	public String update(Patient patient, String startTimeStr, String endTimeStr) {
		if (StringUtils.isNotBlank(startTimeStr)) {
			SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
			try {
				patient.setStartTime(format.parse(startTimeStr));
			} catch (ParseException e) {
				patient.setStartTime(new Date());
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		this.patientService.saveEntity(patient);
		return Boolean.TRUE.toString().toLowerCase();
	}

	@ResponseBody
	@RequestMapping("/delete.action")
	public String delete(Bed bed) {
		this.bedService.deleteEntity(bed);
		return new EasyUiMessage().toString();
	}
	@ResponseBody
	@RequestMapping("/deleteByName.action")
	public String deleteByName(String bedid,HttpSession session) {
		java.util.List<Bed> lstBed=this.bedService.findList("from Bed t where t.id=? and t.user.id=?", bedid,((TUser)session.getAttribute(UserContext.USER_ATTR)).getId());
		if(lstBed.size()>0) {
			Bed bed=lstBed.get(0);
			Patient patient = this.patientService.findByBedIdAndEndTimeIsNull(bed.getId());
			if(patient!=null){
				this.patientBedUserService.deleteByBedIdAndPatientId(bed.getId(),patient.getId());
				this.patientService.deleteByBedId(bed.getId());
			}
			this.bedService.deleteByIdofBedbysql(bed.getId());
			//this.bedService.deleteEntity(bed);//用这种方式会出现问题：上边两个都删除了，但是是事务型的，用这种方式，bed表认为还没删除以上数据，会出现冲突
		}
		return new EasyUiMessage().toString();
	}
}